package com.hwadee.property.controller.house;

import com.hwadee.property.pojo.Community;
import com.hwadee.property.service.ICommunityService;
import com.hwadee.property.util.AjaxResult;
import com.hwadee.property.util.JwtUtil;
import com.hwadee.property.dto.PageResult;
import com.hwadee.property.util.FileUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/community")
@Api(tags = "小区-CommunityController")
@CrossOrigin
public class CommunityController {

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private FileUtil fileUtil;

    @ApiOperation(value = "【管理员】根据小区ID查询小区信息", notes = "根据小区ID查询小区信息")
    @ApiImplicitParam(name = "communityId", value = "小区ID", required = true, dataType = "long", paramType = "path")
    @GetMapping("/{communityId}")
    public AjaxResult getCommunityById(@RequestHeader("Authorization") String token, @PathVariable Long communityId) {
        // 查询小区信息
        Community community = communityService.getById(communityId);
        if (community != null) {
            return AjaxResult.success(community);
        } else {
            return AjaxResult.fail("未找到对应的小区信息");
        }
    }


    @ApiOperation(value = "【用户】获取个人小区信息", notes = "返回个人所属的小区信息列表")
    @GetMapping("/personal")
    public AjaxResult getPersonalCommunities(@RequestHeader("Authorization") String token) {
        // 如果 token 为空，返回错误
        if (token == null || token.isEmpty()) {
            return AjaxResult.fail("未授权, token 为空");
        }

        try {
            // 从 token 中解析出用户 ID
            Long userId = jwtUtil.getUserId(token);
            // 获取用户所属的小区信息
            List<Community> communities = communityService.listByUserId(userId);
            return AjaxResult.success(communities);
        } catch (Exception e) {
            // token 解析异常或其他异常，返回失败
            return AjaxResult.fail("token 解析异常或其他异常，获取个人小区信息失败");
        }
    }


    @ApiOperation(value = "【管理员】获取小区信息列表(模糊查询)", notes = "根据小区名称模糊查询小区信息")
    @ApiImplicitParam(name = "name", value = "小区名称", required = false, dataType = "String", paramType = "query")
    @GetMapping("/search")
    public AjaxResult getByName(@RequestHeader("Authorization") String token, @RequestParam(value = "name", required = false) String communityName) {
        List<Community> list = (communityName == null || communityName.isEmpty())
                ? communityService.list()
                : communityService.getByName(communityName);
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "【管理员】分页查询小区信息", notes = "分页查询小区信息，支持排序和过滤")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, defaultValue = "1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页大小", required = true, defaultValue = "10", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "小区名称", required = false, dataType = "String", paramType = "query")
    })
    @GetMapping("/page")
    public AjaxResult getPage(@RequestHeader("Authorization") String token,
            @RequestParam(value = "current", defaultValue = "1") int current,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "name", required = false) String name) {
        PageResult<Community> pageResult = communityService.getPage(current, size, name);
        return AjaxResult.success(pageResult);
    }

    /**
     * 【管理员】添加小区信息
     *
     * @param token          认证令牌
     * @param communityName  小区名称
     * @param address        小区地址
     * @param totalBuildings 总楼栋数
     * @param totalHouseholds 总住户数
     * @param developer      开发商
     * @param estateCompany  物业公司
     * @param thumbnail      小区缩略图（可选）
     * @return 操作结果
     */
    @ApiOperation(value = "【管理员】添加小区信息", notes = "添加一个新的小区信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证令牌", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "communityName", value = "小区名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "小区地址", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "totalBuildings", value = "总楼栋数", required = true, dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "totalHouseholds", value = "总住户数", required = true, dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "developer", value = "开发商", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "estateCompany", value = "物业公司", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "thumbnail", value = "小区缩略图", required = false, dataType = "file", paramType = "form")
    })
    @PostMapping
    public AjaxResult addCommunity(
            @RequestHeader("Authorization") String token,
            @RequestParam String communityName,
            @RequestParam String address,
            @RequestParam Integer totalBuildings,
            @RequestParam Integer totalHouseholds,
            @RequestParam String developer,
            @RequestParam String estateCompany,
            @RequestParam(required = false) MultipartFile thumbnail) {

        Community community = new Community();
        community.setCommunityName(communityName);
        community.setAddress(address);
        community.setTotalBuildings(totalBuildings);
        community.setTotalHouseholds(totalHouseholds);
        community.setDeveloper(developer);
        community.setEstateCompany(estateCompany);

        if (thumbnail != null) {
            String thumbnailPath = fileUtil.uploadFileAndGetPath(thumbnail, "thumbnail");
            community.setThumbnail(thumbnailPath);
        }

        boolean result = communityService.addCommunity(community);
        return result ? AjaxResult.success() : AjaxResult.fail("添加小区失败");
    }

    /**
     * 【管理员】更新小区信息
     *
     * @param token          认证令牌
     * @param communityId    小区ID
     * @param communityName  小区名称（可选）
     * @param address        小区地址（可选）
     * @param totalBuildings 总楼栋数（可选）
     * @param totalHouseholds 总住户数（可选）
     * @param developer      开发商（可选）
     * @param estateCompany  物业公司（可选）
     * @param thumbnail      小区缩略图（可选）
     * @return 操作结果
     */
    @ApiOperation(value = "【管理员】更新小区信息", notes = "根据小区ID更新小区信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证令牌", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "communityId", value = "小区ID", required = true, dataType = "long", paramType = "path"),
            @ApiImplicitParam(name = "communityName", value = "小区名称", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "小区地址", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "totalBuildings", value = "总楼栋数", required = false, dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "totalHouseholds", value = "总住户数", required = false, dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "developer", value = "开发商", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "estateCompany", value = "物业公司", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "thumbnail", value = "小区缩略图", required = false, dataType = "file", paramType = "form")
    })
    @PutMapping("/{communityId}")
    public AjaxResult updateCommunity(
            @RequestHeader("Authorization") String token,
            @PathVariable Long communityId,
            @RequestParam(required = false) String communityName,
            @RequestParam(required = false) String address,
            @RequestParam(required = false) Integer totalBuildings,
            @RequestParam(required = false) Integer totalHouseholds,
            @RequestParam(required = false) String developer,
            @RequestParam(required = false) String estateCompany,
            @RequestParam(required = false) MultipartFile thumbnail) {

        Community community = new Community();
        community.setId(communityId);
        if (communityName != null) community.setCommunityName(communityName);
        if (address != null) community.setAddress(address);
        if (totalBuildings != null) community.setTotalBuildings(totalBuildings);
        if (totalHouseholds != null) community.setTotalHouseholds(totalHouseholds);
        if (developer != null) community.setDeveloper(developer);
        if (estateCompany != null) community.setEstateCompany(estateCompany);

        if (thumbnail != null) {
            String thumbnailPath = fileUtil.checkIfExist(communityService.getById(communityId).getThumbnail(), "thumbnail");
            if (thumbnailPath != null) {
                fileUtil.deleteOldFile(thumbnailPath, "thumbnail");
            }
            thumbnailPath = fileUtil.uploadFileAndGetPath(thumbnail, "thumbnail");
            community.setThumbnail(thumbnailPath);
        }

        boolean result = communityService.updateCommunity(community);
        return result ? AjaxResult.success() : AjaxResult.fail("更新小区失败");
    }

    @ApiOperation(value = "【管理员】删除小区信息", notes = "根据小区ID删除小区信息")
    @ApiImplicitParam(name = "communityId", value = "小区ID", required = true, dataType = "Long", paramType = "path")
    @DeleteMapping("/{communityId}")
    public AjaxResult deleteCommunity(@RequestHeader("Authorization") String token, @PathVariable Long communityId) {
        String thumbnail = communityService.getById(communityId).getThumbnail();
        if (thumbnail != null){
            String thumbnailPath = fileUtil.checkIfExist(communityService.getById(communityId).getThumbnail(), "thumbnail");
            if (thumbnailPath != null){
                fileUtil.deleteOldFile(thumbnailPath, "thumbnail");
            }
        }
        boolean result = communityService.deleteCommunity(communityId);
        return result ? AjaxResult.success() : AjaxResult.fail("删除小区失败");
    }
}
